﻿using DiamondDash.Core;
using DiamondDash.Entities;
using DiamondDash.Pages;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;
using System.Windows.Threading;

namespace DiamondDash.Views
{
    /// <summary>
    /// 游戏画板类
    /// </summary>
    public class GameCanvas : Canvas
    {
        //常量
        const int DOWN_DURATION = 90;

        int[,] datas;
        DiamondItemView[,] itemViews;
        OpRespItemView[,] opItemViews;
        Random r = new Random(DateTime.Now.Millisecond);
        object clickSyncObj = new object();
        bool isEliminating = false;
        int combo = 1;
        DispatcherTimer timerCombo;
        object currentComboTimerTickSyncObj = new object();
        int currentComboTimerTick = 0;
        bool isEliminateInTheTick = false;
        bool isTooled = false;

        List<int> toolsenceIndexLst = new List<int>();

        public GameCanvas()
        {
            this.MouseLeftButtonDown += GameCanvas_MouseLeftButtonDown;
            timerCombo = new DispatcherTimer();
            timerCombo.Interval = TimeSpan.FromMilliseconds(137);
            timerCombo.Tick += timerCombo_Tick;
        }

        void timerCombo_Tick(object sender, EventArgs e)
        {
            lock (currentComboTimerTickSyncObj)
            {
                currentComboTimerTick++;
                if (currentComboTimerTick >= 5)
                {
                    currentComboTimerTick = 0;
                    if (!isEliminateInTheTick)
                    {
                        //中断Combo
                        if (!GamePage.Instance.IsFireMode)
                        {
                            combo = 1;
                        }
                    }
                    isEliminateInTheTick = false;
                }
            }
        }

        void GameCanvas_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (GamePage.Instance.gameStatus != 1)
            {
                return;
            }

            lock (clickSyncObj)
            {
                if (isEliminating)
                {
                    return;
                }
            }

            isEliminating = true;

            Point p = e.GetPosition(this);
            int row = (int)(p.Y / GameStatics.ItemHeight);
            int column = (int)(p.X / GameStatics.ItemWidth);

            if (row < 0 || row > GameStatics.RowCount - 1 || column < 0 || column > GameStatics.ColumnCount - 1)
            {
                isEliminating = false;
                return;
            }

            //先判断是否点击的超级钻石
            if (datas[row, column] == 6)
            {
                //把当行和当列的数据全部消除
                List<int> tempSelectItems = new List<int>();
                for (int i = 0; i < GameStatics.RowCount; i++)
                {
                    tempSelectItems.Add(i * GameStatics.ColumnCount + column);
                }
                for (int i = 0; i < GameStatics.ColumnCount; i++)
                {
                    tempSelectItems.Add(row * GameStatics.ColumnCount + i);
                }
                EliminateProcess(tempSelectItems, true, 0);
            }
            else
            {

                List<int> tempSelectItems = new List<int>();
                tempSelectItems.Add(row * GameStatics.ColumnCount + column);
                //找到所有相关的色块，并全部选中，需要递归调用
                FindRelationGameItem(datas[row, column], row, column, FindType.All, tempSelectItems);

                if (tempSelectItems.Count > 2)
                {
                    //判断是否有道具控件

                    //TODO lc 道具效果
                    int tool = GetToolInSelect(tempSelectItems);
                    if (tool == 1)
                    {
                        //爆炸道具，扩大选取范围
                        DealBombProcess(tempSelectItems);
                    }

                    EliminateProcess(tempSelectItems, false, tool);
                }
                else
                {
                    //TODO 不能消除，断开combo，显示选错状态
                    foreach (var itemIndex in tempSelectItems)
                    {
                        int itemRow = itemIndex / GameStatics.ColumnCount;
                        int itemColumn = itemIndex % GameStatics.ColumnCount;
                        opItemViews[itemRow, itemColumn].ShowOpResp(true);
                    }
                    lock (clickSyncObj)
                    {
                        isEliminating = false;
                    }
                    GamePage.Instance.ErrorEliminate();
                }
            }
        }

        private int GetToolInSelect(List<int> tempSelectItems)
        {
            int result = 0;
            foreach (var itemIndex in tempSelectItems)
            {
                int itemRow = itemIndex / GameStatics.ColumnCount;
                int itemColumn = itemIndex % GameStatics.ColumnCount;

                if (itemViews[itemRow, itemColumn].IsTooled)
                {
                    result = itemViews[itemRow, itemColumn].ToolType;
                    break;
                }
            }
            return result;
        }

        /// <summary>
        /// 消除步骤
        /// </summary>
        /// <param name="tempSelectItems"></param>
        private void EliminateProcess(List<int> tempSelectItems, bool isUseSuperDiamonde, int tool)
        {
            List<int> columns = new List<int>();
            int color = 1;

            //可以进行消除
            //先使用简单的方法直接进行更换

            //音效
            if (tool != 1)
            {
                PlayEliminateSound(combo, GamePage.Instance.IsFireMode);
            }
            else
            {
                SoundManager.PlayEffect(SoundManager.bombEliminate);
            }

            //FireMode
            if (tool == 0 && GamePage.Instance.IsFireMode && !isUseSuperDiamonde)
            {
                DealBombProcess(tempSelectItems);
            }

            foreach (var itemIndex in tempSelectItems)
            {
                int itemRow = itemIndex / GameStatics.ColumnCount;
                int itemColumn = itemIndex % GameStatics.ColumnCount;

                color = datas[itemRow, itemColumn];

                if (datas[itemRow, itemColumn] == 6)
                {
                    itemViews[itemRow, itemColumn].UseSuperDiamond();
                }


                //设置为空
                datas[itemRow, itemColumn] = 0;
                itemViews[itemRow, itemColumn].Hide();

                opItemViews[itemRow, itemColumn].ShowOpResp();

                if (!columns.Contains(itemColumn))
                {
                    columns.Add(itemColumn);
                }
            }

            DispatcherTimer moveTimer = new DispatcherTimer();
            moveTimer.Interval = TimeSpan.FromMilliseconds(8);
            moveTimer.Tick += (object s, EventArgs ee) =>
            {
                moveTimer.Stop();
                foreach (var c in columns)
                {
                    MoveBottom(c);
                }

                //消除之后补充新的
                AddNewDiamond();
                CheckCanEliminate();

                DispatcherTimer clickReleaseTimer = new DispatcherTimer();
                clickReleaseTimer.Interval = TimeSpan.FromMilliseconds(DOWN_DURATION);
                clickReleaseTimer.Tick += (object ss, EventArgs eee) =>
                {

                    clickReleaseTimer.Stop();
                    //加分
                    GamePage.Instance.EliminateDiamond(tempSelectItems.Count, combo, isUseSuperDiamonde);
                    //Combo
                    lock (currentComboTimerTickSyncObj)
                    {
                        if (combo < 11)
                        {
                            combo++;
                            if (combo == 11)
                            {
                                //启动Firemode
                                GamePage.Instance.ToFireMode();
                            }
                        }
                        isEliminateInTheTick = true;
                        currentComboTimerTick = 0;
                    }
                    //使用道具
                    switch (tool)
                    {
                        case 2:
                            DealTimeProcess();
                            break;
                        case 3:
                            DealColorProcess(color);
                            break;
                    }
                    if (tool > 0)
                    {
                        isTooled = false;
                        //清除sense
                        foreach (var item in toolsenceIndexLst)
                        {
                            int rr = item / GameStatics.ColumnCount;
                            int cc = item % GameStatics.ColumnCount;
                            itemViews[rr, cc].ClearSence();
                            itemViews[rr, cc].ClearToolItem();
                        }
                        toolsenceIndexLst.Clear();
                    }

                    lock (clickSyncObj)
                    {
                        isEliminating = false;
                    }
                };
                clickReleaseTimer.Start();
            };
            moveTimer.Start();
        }

        /// <summary>
        /// 播放消除音效
        /// </summary>
        /// <param name="combo"></param>
        /// <param name="p"></param>
        private void PlayEliminateSound(int combo, bool isFireMode)
        {
            if (isFireMode)
            {
                SoundManager.PlayEffect(SoundManager.eliminate12);
            }
            else
            {
                int id = SoundManager.eliminate1;
                switch (combo)
                {
                    case 1:
                        id = SoundManager.eliminate1;
                        break;
                    case 2:
                        id = SoundManager.eliminate2;
                        break;
                    case 3:
                        id = SoundManager.eliminate3;
                        break;
                    case 4:
                        id = SoundManager.eliminate4;
                        break;
                    case 5:
                        id = SoundManager.eliminate5;
                        break;
                    case 6:
                        id = SoundManager.eliminate6;
                        break;
                    case 7:
                        id = SoundManager.eliminate7;
                        break;
                    case 8:
                        id = SoundManager.eliminate8;
                        break;
                    case 9:
                        id = SoundManager.eliminate9;
                        break;
                    case 10:
                        id = SoundManager.eliminate10;
                        break;
                    case 11:
                        id = SoundManager.eliminate11;
                        break;
                }
                SoundManager.PlayEffect(id);
            }
        }

        /// <summary>
        /// 重新开始游戏
        /// </summary>
        public void RestartGame()
        {
            toolsenceIndexLst.Clear();
            isTooled = false;
            combo = 1;
            isEliminating = false;
            isEliminateInTheTick = false;

            int canEliminateCount = 0;
            while (canEliminateCount < 2)
            {
                for (int i = 0; i < GameStatics.RowCount; i++)
                {
                    for (int j = 0; j < GameStatics.ColumnCount; j++)
                    {
                        datas[i, j] = r.Next(5) + 1;
                    }
                }
                canEliminateCount = GetAvailableEliminateCount();
            }

            for (int i = 0; i < GameStatics.RowCount; i++)
            {
                for (int j = 0; j < GameStatics.ColumnCount; j++)
                {
                    itemViews[i, j].SetColor(datas[i, j]);
                }
            }
            timerCombo.Start();
        }

        /// <summary>
        /// 开始游戏
        /// </summary>
        public void StartNewGame()
        {
            toolsenceIndexLst.Clear();
            isTooled = false;
            combo = 1;
            isEliminating = false;
            isEliminateInTheTick = false;
            datas = new int[GameStatics.RowCount, GameStatics.ColumnCount];
            itemViews = new DiamondItemView[GameStatics.RowCount, GameStatics.ColumnCount];
            opItemViews = new OpRespItemView[GameStatics.RowCount, GameStatics.ColumnCount];

            int canEliminateCount = 0;
            while (canEliminateCount < 2)
            {
                for (int i = 0; i < GameStatics.RowCount; i++)
                {
                    for (int j = 0; j < GameStatics.ColumnCount; j++)
                    {
                        datas[i, j] = r.Next(5) + 1;
                    }
                }
                canEliminateCount = GetAvailableEliminateCount();
            }


            for (int i = 0; i < GameStatics.RowCount; i++)
            {
                for (int j = 0; j < GameStatics.ColumnCount; j++)
                {
                    DiamondItemView view = new DiamondItemView();
                    view.SetColor(datas[i, j]);
                    itemViews[i, j] = view;

                    //设置显示的位置
                    Canvas.SetLeft(view, j * GameStatics.ItemWidth);
                    Canvas.SetTop(view, i * GameStatics.ItemHeight);
                    Canvas.SetZIndex(view, 1);
                    this.Children.Add(view);

                    OpRespItemView opView = new OpRespItemView();
                    opItemViews[i, j] = opView;

                    //设置显示的位置
                    Canvas.SetLeft(opView, j * GameStatics.ItemWidth);
                    Canvas.SetTop(opView, i * GameStatics.ItemHeight);
                    Canvas.SetZIndex(opView, 2);
                    this.Children.Add(opView);
                }
            }
            timerCombo.Start();
        }

        /// <summary>
        /// 暂停游戏s
        /// </summary>
        public void PauseGame()
        {
            timerCombo.Stop();
        }

        /// <summary>
        /// 结束游戏
        /// </summary>
        public void EndGame()
        {
            timerCombo.Stop();
        }

        /// <summary>
        /// 继续游戏
        /// </summary>
        public void ResumeGame()
        {
            timerCombo.Start();
        }

        /// <summary>
        /// 检查能否有多个消除位，如果少于1个则自动增加一个消除块
        /// </summary>
        private void CheckCanEliminate()
        {
            //如果存在超级钻石，不需要处理
            if (!IsHaveSuperDiamond())
            {
                //检查现在能消除的个数，如果小于1个，则在随机选择3个单元格变成同一个色块
                int currentBlockCount = GetAvailableEliminateCount();
                if (currentBlockCount < 1)
                {
                    //选择3个单元格
                    int startRow = r.Next(GameStatics.RowCount - 1);
                    int startColumn = r.Next(GameStatics.ColumnCount - 1);

                    int type = r.Next(5) + 1;
                    datas[startRow, startColumn] = type;
                    datas[startRow + 1, startColumn] = type;
                    datas[startRow, startColumn + 1] = type;

                    itemViews[startRow, startColumn].ChangeColor(type);
                    itemViews[startRow + 1, startColumn].ChangeColor(type);
                    itemViews[startRow, startColumn + 1].ChangeColor(type);
                }
            }
        }

        /// <summary>
        /// 向下移动
        /// </summary>
        /// <param name="column"></param>
        /// <returns></returns>
        private double MoveBottom(int column)
        {
            double result = 0;
            List<DiamondChangeInfo> needToExchange = new List<DiamondChangeInfo>();

            // 找到一个空的，往后寻找，找到替换，没找到break
            for (int i = GameStatics.RowCount - 1; i >= 0; i--)
            {
                int data = datas[i, column];
                if (data == 0)
                {
                    DiamondChangeInfo findInfo = new DiamondChangeInfo();
                    findInfo.StartX = -1;
                    findInfo.StartY = -1;
                    findInfo.EndX = -1;
                    findInfo.EndY = -1;

                    for (int ii = i - 1; ii >= 0; ii--)
                    {
                        int tempData = datas[ii, column];
                        if (tempData > 0)
                        {
                            findInfo.EndX = i;
                            findInfo.EndY = column;
                            findInfo.StartX = ii;
                            findInfo.StartY = column;
                            break;
                        }
                    }
                    if (findInfo.StartX != -1 && findInfo.EndX != -1)
                    {
                        //更新datas
                        int temp = datas[findInfo.StartX, findInfo.StartY];
                        datas[findInfo.StartX, findInfo.StartY] = datas[findInfo.EndX, findInfo.EndY];
                        datas[findInfo.EndX, findInfo.EndY] = temp;
                        needToExchange.Add(findInfo);
                    }
                    else
                    {
                        break;
                    }
                }
            }
            // 互换并更新界面
            result = ExchangeDiamond(needToExchange);
            bool iscleared = false;
            foreach (var findInfo in needToExchange)
            {
                //更新runes
                DiamondItemView itemTemp = itemViews[findInfo.StartX, findInfo.StartY];
                itemViews[findInfo.StartX, findInfo.StartY] = itemViews[findInfo.EndX, findInfo.EndY];
                itemViews[findInfo.EndX, findInfo.EndY] = itemTemp;

                if (!iscleared)
                {
                    if (itemViews[findInfo.StartX, findInfo.StartY].ClearToolItem()
                        || itemViews[findInfo.EndX, findInfo.EndY].ClearToolItem()
                        || itemViews[findInfo.EndX, findInfo.EndY].IsSence
                        || itemViews[findInfo.StartX, findInfo.StartY].IsSence)
                    {
                        //记录当前没有道具了
                        isTooled = false;
                        //清除sense和道具
                        foreach (var item in toolsenceIndexLst)
                        {
                            int rr = item / GameStatics.ColumnCount;
                            int cc = item % GameStatics.ColumnCount;
                            itemViews[rr, cc].ClearToolItem();
                            itemViews[rr, cc].ClearSence();
                        }
                        toolsenceIndexLst.Clear();
                        iscleared = true;
                    }
                }
                if (itemViews[findInfo.EndX, findInfo.EndY].IsSence)
                {
                    itemViews[findInfo.EndX, findInfo.EndY].ClearSence();
                }
                if (itemViews[findInfo.StartX, findInfo.StartY].IsSence)
                {
                    itemViews[findInfo.StartX, findInfo.StartY].ClearSence();
                }
            }

            return result;
        }

        private void AddNewDiamond()
        {
            int maxColumnBlank = 0;
            int columnBlank = 0;
            //增加新的钻石
            for (int j = 0; j < GameStatics.ColumnCount; j++)
            {
                for (int i = 0; i < GameStatics.RowCount; i++)
                {
                    if (i == 0)
                    {
                        columnBlank = 0;
                        //计算每一列的空缺
                        for (int k = 0; k < GameStatics.RowCount; k++)
                        {
                            if (datas[k, j] == 0)
                            {
                                columnBlank++;
                            }
                        }
                    }
                    if (datas[i, j] == 0)
                    {
                        if (columnBlank > maxColumnBlank)
                        {
                            maxColumnBlank = columnBlank;
                        }
                        //补数据
                        datas[i, j] = r.Next(5) + 1;
                        itemViews[i, j].SetColor(datas[i, j]);
                        itemViews[i, j].Show();

                        //重新设置位置
                        Canvas.SetTop(itemViews[i, j], i * GameStatics.ItemHeight);
                        Canvas.SetLeft(itemViews[i, j], j * GameStatics.ItemWidth);
                    }
                }
            }


        }

        /// <summary>
        /// 交换钻石
        /// </summary>
        /// <param name="needToExchange"></param>
        /// <param name="isOp"></param>
        /// <returns>返回动画结束的毫秒信息</returns>
        private double ExchangeDiamond(List<DiamondChangeInfo> needToExchange)
        {
            double maxDuration = 0;
            foreach (var item in needToExchange)
            {
                //做动画改变位置
                DiamondItemView diamondItem = itemViews[item.StartX, item.StartY];
                //if (diamondItem.IsRuneEnable)
                if (true)
                {
                    Storyboard storyBoard = new Storyboard();
                    double durations = DOWN_DURATION;
                    Duration duration = new Duration(TimeSpan.FromMilliseconds(durations));

                    if (durations > maxDuration)
                    {
                        maxDuration = durations;
                    }

                    DoubleAnimation daX = new DoubleAnimation();
                    daX.Duration = duration;
                    daX.To = item.EndX * GameStatics.ItemWidth;
                    DoubleAnimation daY = new DoubleAnimation();
                    daY.Duration = duration;
                    daY.To = item.EndY * GameStatics.ItemHeight;

                    //特效
                    //ExponentialEase exponential = new ExponentialEase();
                    //exponential.EasingMode = EasingMode.EaseIn;
                    //exponential.Exponent = 2;
                    //daX.EasingFunction = exponential;
                    //daY.EasingFunction = exponential;

                    Storyboard.SetTarget(storyBoard, diamondItem);
                    Storyboard.SetTargetProperty(daX, new PropertyPath(Canvas.TopProperty));
                    Storyboard.SetTargetProperty(daY, new PropertyPath(Canvas.LeftProperty));
                    storyBoard.Children.Add(daX);
                    storyBoard.Children.Add(daY);

                    storyBoard.Begin();
                }
            }

            return maxDuration;
        }

        private int GetAvailableEliminateCount()
        {
            List<int> isSearchedList = new List<int>();
            List<int> tempSelectItems = new List<int>();
            int count = 0;

            for (int i = 0; i < GameStatics.RowCount; i++)
            {
                for (int j = 0; j < GameStatics.ColumnCount; j++)
                {
                    int index = i * GameStatics.ColumnCount + j;

                    if (!isSearchedList.Contains(index))
                    {
                        tempSelectItems.Clear();
                        tempSelectItems.Add(index);
                        //找到所有相关的色块，并全部选中，需要递归调用
                        FindRelationGameItem(datas[i, j], i, j, FindType.All, tempSelectItems);
                        if (tempSelectItems.Count > 2)
                        {
                            count++;
                            foreach (var item in tempSelectItems)
                            {
                                if (!isSearchedList.Contains(item))
                                {
                                    isSearchedList.Add(item);
                                }
                            }
                        }
                    }
                }
            }

            return count;
        }

        private List<List<int>> GetAvailableEliminate()
        {
            List<int> isSearchedList = new List<int>();
            List<int> tempSelectItems = null;
            List<List<int>> result = new List<List<int>>();

            for (int i = 0; i < GameStatics.RowCount; i++)
            {
                for (int j = 0; j < GameStatics.ColumnCount; j++)
                {
                    int index = i * GameStatics.ColumnCount + j;

                    if (!isSearchedList.Contains(index))
                    {
                        tempSelectItems = new List<int>();
                        tempSelectItems.Add(index);
                        //找到所有相关的色块，并全部选中，需要递归调用
                        FindRelationGameItem(datas[i, j], i, j, FindType.All, tempSelectItems);
                        if (tempSelectItems.Count > 2)
                        {
                            result.Add(tempSelectItems);
                            foreach (var item in tempSelectItems)
                            {
                                if (!isSearchedList.Contains(item))
                                {
                                    isSearchedList.Add(item);
                                }
                            }
                        }
                    }
                }
            }

            return result;
        }

        /// <summary>
        /// 递归寻找逻辑
        /// </summary>
        /// <param name="itemType"></param>
        /// <param name="row"></param>
        /// <param name="column"></param>
        /// <param name="findType"></param>
        /// <param name="items"></param>
        private void FindRelationGameItem(int itemType, int row, int column, FindType findType, List<int> items)
        {
            if (findType != FindType.Bottom)
            {
                //向上找
                if (row - 1 >= 0)
                {
                    if (datas[row - 1, column] == itemType)
                    {
                        int itemKey = (row - 1) * GameStatics.ColumnCount + column;
                        if (!items.Contains(itemKey))
                        {
                            items.Add(itemKey);
                            //继续找
                            FindRelationGameItem(itemType, row - 1, column, FindType.Top, items);
                        }
                    }
                }
            }
            if (findType != FindType.Top)
            {
                //向下找
                if (row + 1 < GameStatics.RowCount)
                {
                    if (datas[row + 1, column] == itemType)
                    {
                        int itemKey = (row + 1) * GameStatics.ColumnCount + column;
                        if (!items.Contains(itemKey))
                        {
                            items.Add(itemKey);
                            //继续找
                            FindRelationGameItem(itemType, row + 1, column, FindType.Bottom, items);
                        }
                    }
                }
            }
            if (findType != FindType.Right)
            {
                //向左找
                if (column - 1 >= 0)
                {
                    if (datas[row, column - 1] == itemType)
                    {
                        int itemKey = row * GameStatics.ColumnCount + column - 1;
                        if (!items.Contains(itemKey))
                        {
                            items.Add(itemKey);
                            //继续找
                            FindRelationGameItem(itemType, row, column - 1, FindType.Left, items);
                        }
                    }
                }
            }

            if (findType != FindType.Left)
            {
                //向右找
                if (column + 1 < GameStatics.ColumnCount)
                {
                    if (datas[row, column + 1] == itemType)
                    {
                        int itemKey = row * GameStatics.ColumnCount + column + 1;
                        if (!items.Contains(itemKey))
                        {
                            items.Add(itemKey);
                            //继续找
                            FindRelationGameItem(itemType, row, column + 1, FindType.Right, items);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 新增一个超级钻石
        /// </summary>
        internal void AddNewSuperDiamond()
        {
            //随机加入一个宝石
            if (GetSuperDiamondCount() < 5)
            {
                int tryCount = 0;
                while (tryCount < 6)
                {
                    int tempColumn = r.Next(GameStatics.ColumnCount);
                    int tempRow = r.Next(GameStatics.RowCount);
                    if (itemViews[tempRow, tempColumn].CurrentType != 6)
                    {
                        datas[tempRow, tempColumn] = 6;
                        itemViews[tempRow, tempColumn].SetColor(6);
                        itemViews[tempRow, tempColumn].ShowSuperDiamond(tempRow, tempColumn);
                        SoundManager.PlayEffect(SoundManager.newSuperDiamond);
                        break;
                    }
                    tryCount++;
                }
            }
        }

        private bool IsHaveSuperDiamond()
        {
            for (int i = 0; i < GameStatics.RowCount; i++)
            {
                for (int j = 0; j < GameStatics.ColumnCount; j++)
                {
                    if (datas[i, j] == 6)
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        private int GetSuperDiamondCount()
        {
            int sum = 0;
            for (int i = 0; i < GameStatics.RowCount; i++)
            {
                for (int j = 0; j < GameStatics.ColumnCount; j++)
                {
                    if (datas[i, j] == 6)
                    {
                        sum++;
                    }
                }
            }
            return sum;
        }

        internal void AddToolToMap(int toolType)
        {
            //获得所有可以增加道具的块信息，随机从中选取一个作为增加道具的池子
            //如果当前没有可用的，则此次不增加道具

            //界面中只能存在一个道具，早用早生成
            //相关联的Block也需要有闪烁提示用户

            //TODO lc 同步控制有点小问题
            int tryCount = 0;
            while (true)
            {
                if (!isEliminating)
                {
                    break;
                }
                else
                {
                    tryCount++;
                    if (tryCount >= 5)
                    {
                        break;
                    }
                }
            }

            if (!isTooled)
            {
                List<List<int>> blocks = GetAvailableEliminate();
                if (blocks.Count > 0)
                {
                    //增加该类型的道具
                    List<int> itemIndexs = blocks[r.Next(blocks.Count)];
                    int itemIndex = itemIndexs[r.Next(itemIndexs.Count)];
                    int itemRow = itemIndex / GameStatics.ColumnCount;
                    int itemColumn = itemIndex % GameStatics.ColumnCount;
                    itemViews[itemRow, itemColumn].SetToolItem(toolType);

                    foreach (var item in itemIndexs)
                    {
                        int rr = item / GameStatics.ColumnCount;
                        int cc = item % GameStatics.ColumnCount;
                        itemViews[rr, cc].SetSence();
                        toolsenceIndexLst.Add(item);
                    }

                    isTooled = true;
                }
            }
        }

        #region 道具处理

        private void DealColorProcess(int color)
        {
            //更换四分之一的钻石
            for (int i = 0; i < GameStatics.RowCount / 2; i++)
            {
                for (int j = 0; j < GameStatics.ColumnCount / 2 + 1; j++)
                {
                    datas[i, j] = color;
                    itemViews[i, j].ChangeColor(color);
                }
            }
            SoundManager.PlayEffect(SoundManager.colorEliminate);
        }

        private void DealTimeProcess()
        {
            GamePage.Instance.AddTime();
        }

        /// <summary>
        /// 处理炸弹道具
        /// </summary>
        /// <param name="tempSelectItems"></param>
        private void DealBombProcess(List<int> tempSelectItems)
        {
            //扩大选取范围
            List<int> addValues = new List<int>();
            foreach (var item in tempSelectItems)
            {
                int r = item / GameStatics.ColumnCount;
                int c = item % GameStatics.ColumnCount;
                //选取周边的四个加入选中

                //左边一个
                if (r > 0)
                {
                    int x = GetIntIndex(r - 1, c);
                    if (!tempSelectItems.Contains(x) && !addValues.Contains(x))
                    {
                        addValues.Add(x);
                    }
                }
                //右边一个
                if (r < GameStatics.RowCount - 1)
                {
                    int x = GetIntIndex(r + 1, c);
                    if (!tempSelectItems.Contains(x) && !addValues.Contains(x))
                    {
                        addValues.Add(x);
                    }
                }
                //上边一个
                if (c > 0)
                {
                    int x = GetIntIndex(r, c - 1);
                    if (!tempSelectItems.Contains(x) && !addValues.Contains(x))
                    {
                        addValues.Add(x);
                    }
                }
                //下边一个
                if (c < GameStatics.ColumnCount - 1)
                {
                    int x = GetIntIndex(r, c + 1);
                    if (!tempSelectItems.Contains(x) && !addValues.Contains(x))
                    {
                        addValues.Add(x);
                    }
                }
            }
            foreach (var item in addValues)
            {
                tempSelectItems.Add(item);
            }
        }

        private int GetIntIndex(int r, int c)
        {
            return r * GameStatics.ColumnCount + c;
        }

        #endregion

        internal void ResetCombo()
        {
            combo = 1;
        }
    }
}
